import  Vue from "vue"
import axios from 'axios'
import store from '@/store/index.js'
const service = axios.create({
	 baseURL: 'https://api-hmugo-web.itheima.net/api/public/v1',
	 timeout: 5000
})

service.interceptors.request.use(function (config) {
	if (config.baseURL.indexOf('/my/') !== -1) {
		config.headers.Authorization = store.state.user.token
	}
    return config
  }, function (error) {
    return Promise.reject(error)
  })
// 响应拦截器
service.interceptors.response.use(function (response) {
    return response.data
  }, function (error) {
    return Promise.reject(error)
})

axios.defaults.adapter = function(config) { //自己定义个适配器，用来适配uniapp的语法
    return new Promise((resolve, reject) => {
        var settle = require('axios/lib/core/settle');
        var buildURL = require('axios/lib/helpers/buildURL');
        uni.request({
            method: config.method.toUpperCase(),
            url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
            header: config.headers,
            data: config.data,
            dataType: config.dataType,
            responseType: config.responseType,
            sslVerify: config.sslVerify,
            complete: function complete(response) {
                response = {
                    data: response.data,
                    status: response.statusCode,
                    errMsg: response.errMsg,
                    header: response.header,
                    config: config
                };

                settle(resolve, reject, response);
            }
        })
    })
}

export default service
